﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;

namespace GlTool.GlHttp
{

    /// <summary>
    /// 模拟浏览器提交表单
    /// </summary>
    public abstract class GlHttpBase
    {

        /// <summary>
        /// Content-Type
        /// </summary>
        private String contentType;

        public String ContentType
        {
            get { return contentType; }
            set { contentType = value; }
        }

        /// <summary>
        /// 设置User-Agent浏览器标识
        /// </summary>
        private String userAgent;

        public String UserAgent
        {
            get { return userAgent; }
            set { userAgent = value; }
        }

        /// <summary>
        /// 允许上传的类型
        /// </summary>
        private String accept;

        public String Accept
        {
            get { return accept; }
            set { accept = value; }
        }

        /// <summary>
        /// 请求url
        /// </summary>
        private String url;
        public String Url { get; set; }


        /// <summary>
        /// 设置超时
        /// </summary>
        private int timeout;

        public int Timeout
        {
            get { return timeout; }
            set { timeout = value; }
        }

        /// <summary>
        /// 问号传值
        /// </summary>
        private Dictionary<String, object> queryMap;

        /// <summary>
        /// 头部信息
        /// </summary>
        private Dictionary<String, object> headMap;

        /// <summary>
        /// cookie值
        /// </summary>
        private Dictionary<String, object> cookieMap;

        /// <summary>
        /// 设置问号传值
        /// </summary>
        /// <param name="key">参数名</param>
        /// <param name="value">参数值</param>
        public void setQueryString(String key, Object value)
        {
            if (queryMap == null)
            {
                queryMap = new Dictionary<string, object>();
            }
            queryMap.Add(key, value);
        }

        /// <summary>
        /// 设置问号传值
        /// </summary>
        /// <param name="queryMap"></param>
        public void setQueryString(Dictionary<String, object> queryMap)
        {
            if (queryMap == null)
            {
                queryMap = new Dictionary<string, object>();
            }

            foreach (var item in queryMap)
            {
                this.queryMap.Add(item.Key, item.Value);
            }
        }

        /// <summary>
        /// 设置头部信息
        /// </summary>
        /// <param name="key">参数名</param>
        /// <param name="value">参数值</param>
        public void setHead(String key, object value)
        {
            if (headMap == null)
            {
                headMap = new Dictionary<string, object>();
            }
            headMap.Add(key, value);
        }

        /// <summary>
        /// 设置头部信息
        /// </summary>
        /// <param name="headMap"></param>
        public void setHead(Dictionary<String, object> headMap)
        {
            if (headMap == null)
            {
                headMap = new Dictionary<string, object>();
            }
            foreach (var item in headMap)
            {
                this.headMap.Add(item.Key, item.Value);
            }
        }

        /// <summary>
        /// 设置cookie
        /// </summary>
        /// <param name="key">参数名</param>
        /// <param name="value">参数值</param>
        public void setCookie(String key, object value)
        {
            if (cookieMap == null)
            {
                cookieMap = new Dictionary<string, object>();
            }
            cookieMap.Add(key, value);
        }

        /// <summary>
        /// 设置cookie
        /// </summary>
        /// <param name="cookieMap"></param>
        public void setCookie(Dictionary<String, object> cookieMap)
        {
            if (cookieMap == null)
            {
                cookieMap = new Dictionary<string, object>();
            }
            foreach (var item in cookieMap)
            {
                this.cookieMap.Add(item.Key, item.Value);
            }
        }

        public abstract GlHttpResponse Execute();

        /// <summary>
        /// 获取请求
        /// </summary>
        /// <returns></returns>
        public HttpWebRequest getRequest()
        {
            String url = Url;

            if (queryMap != null && queryMap.Count > 0)
            {

                //拼出问号传值
                StringBuilder querySb = new StringBuilder();
                foreach (var item in queryMap)
                {
                    if (querySb.Length > 0)
                    {
                        querySb.Append("&");
                    }
                    querySb.Append(item.Key).Append('=').Append(item.Value);
                }

                if (url.IndexOf("?") == -1)
                {
                    url = url + "?" + querySb.ToString();
                }
                else
                {
                    url = url + "&" + querySb.ToString();
                }
            }

            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);



            //if (cookieMap != null && cookieMap.Count > 0)
            //{
            //    //设置cookie
            //    CookieContainer cc = new CookieContainer();
            //    foreach (var item in cookieMap)
            //    {
            //        Cookie cookie = new Cookie(item.Key, item.Value + "");
            //        cookie.Domain = "192.168.1.155";
            //        cc.Add(cookie);
            //    }
            //    request.CookieContainer = cc;
            //}

            if (cookieMap != null && cookieMap.Count > 0)
            {
                //设置cookie

                StringBuilder cookieSb = new StringBuilder();
                foreach (var item in cookieMap)
                {
                    cookieSb.Append(item.Key).Append('=').Append(item.Value + "").Append(';');
                }
                this.setHead("Cookie", cookieSb.ToString());
            }

            if (headMap != null && headMap.Count > 0)
            {
                //设置头部信息
                foreach (var item in headMap)
                {
                    //过滤掉不允许通过header来设置的几个属性

                    switch (item.Key.Trim().ToLower())
                    {
                        case "content-type":
                            request.ContentType = item.Value + "";
                            break;

                        case "user-agent":
                            request.UserAgent = item.Value + "";
                            break;

                        case "accept":
                            request.Accept = item.Value + "";
                            break;

                        default:
                            request.Headers.Set(item.Key, item.Value + ""); break;
                    }
                }
            }

            //请求的身份验证信息为默认  
            request.Credentials = CredentialCache.DefaultCredentials;
            return request;
        }


        public String test()
        {

            //创建请求  
            var request = (HttpWebRequest)HttpWebRequest.Create(url);
            request.Method = "GET";

            //request.Headers.Set();


            //请求的身份验证信息为默认  
            request.Credentials = CredentialCache.DefaultCredentials;

            //请求超时时间  
            request.Timeout = 10000;
            //读取返回消息  
            string res;
            try
            {
                var response = (HttpWebResponse)request.GetResponse();
                var reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                res = reader.ReadToEnd();
                reader.Close();
            }
            catch (Exception ex)
            {
                //var result = new ServerResult();
                return "{\"error\":\"connectToServer\",\"error_description\":\"" + ex.Message + "\"}";
            }
            return res;
        }

    }
}
